package cc.ccoke.swingutils.dot_matrix.gui;

import cc.ccoke.swingutils.dot_matrix.entity.DotMatrix;
import cc.ccoke.swingutils.dot_matrix.filter.FileEndFilter;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ccoke
 * @Description:
 * @Date: Created in 下午5:40 18-6-14
 * http://www.afterturn.cn/doc/easypoi.html
 **/
@Data
public class DotMatrixGUI implements ActionListener {
    private static final String FILE_ERROR = "文件格式错误";
    private static final String SUCCESS = "文件解析成功";
    private static final String ERROR = "文件解析失败，请检查文件后重试";
    private static final String START_WITH = "var arr = [";
    private static final String END_WITH = "];";
    private static final String LEFT_BRACKET = "[";
    private static final String RIGHT_BRACKET = "],";

    private JButton chooseButton;
    private JPanel parentPanel;
    private JLabel messageLabel;
    private JFileChooser fileChooser = new JFileChooser();
    private String currentDir;

    public DotMatrixGUI() {
        chooseButton.addActionListener(this);
        fileChooser.setFileFilter(new FileEndFilter());
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(chooseButton)){
            fileChooser.setFileSelectionMode(0);
            if (currentDir != null){
                fileChooser.setCurrentDirectory(new File(currentDir));
            }
            int state = fileChooser.showOpenDialog(null);
            if (state == 1) {
                return;
            } else {
                File file = fileChooser.getSelectedFile();
                currentDir = file.getParent();
                if (fileNotXLS(file.getName())){
                    messageLabel.setText(FILE_ERROR);
                }else {
                    messageLabel.setText(file.getName());
                    // 解析xls
                    List<DotMatrix> numberList = load(file);
                    if (numberList == null || numberList.size() < 1) {
                        messageLabel.setText(FILE_ERROR);
                    }else {
                        // 过滤
                        List<DotMatrix> dotMatrices = filter(numberList);
                        // 导出
                        String fileName = file.getName().substring(0, file.getName().lastIndexOf(".")) + ".js";
                        String filePath = currentDir + File.separator + fileName;
                        File newFile = new File(filePath);
                        if (export(dotMatrices, newFile)){
                            messageLabel.setText(SUCCESS + ":" + filePath);
                            // 打开文件所在目录
                            try {
                                Runtime.getRuntime().exec(
                                        "rundll32 SHELL32.DLL,ShellExec_RunDLL "
                                                + "Explorer.exe /select," + newFile.getAbsolutePath());
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }else {
                            messageLabel.setText(ERROR);
                        }
                    }
                }
            }
        }
    }


    private boolean export(List<DotMatrix> dotMatrices, File file) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(file);
            fw.write(START_WITH);
            for (DotMatrix domatrix : dotMatrices) {
                fw.write(LEFT_BRACKET);
                fw.write(domatrix.getMatrix());
                fw.write(RIGHT_BRACKET);
                fw.flush();
            }
            fw.write(END_WITH);
            fw.flush();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    private List<DotMatrix> filter(List<DotMatrix> numberList) {
        List<DotMatrix> list = new ArrayList<>();
        for (DotMatrix point: numberList) {
            list.add(point);
        }
        return list;
    }



    private List<DotMatrix> load(File file) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        try {
            List<DotMatrix> list = ExcelImportUtil.importExcel(file, DotMatrix.class, params);
            return list;
        }catch (ExcelImportException e){
            messageLabel.setText(FILE_ERROR);
            return null;
        }
    }

    // 判断文件是否为xls
    private boolean fileNotXLS(String filename){
        return "".equals(filename.trim()) || !(filename.endsWith(".xls") || filename.endsWith(".xlsx"))? true : false;
    }

}
